#include "stdafx.h"
#include "AutoThreshold.h"

AutoThreshold::AutoThreshold()
{}
AutoThreshold::~AutoThreshold()
{}

void AutoThreshold::GetPiTable(vector<unsigned int> v)
{
	u=0;
	for (int i=0;i<256;i++)
	{
		Pi[i]=(double)v[i]/(double)(Height*Width*Frames);
		u+=i*Pi[i];
	}
}

int AutoThreshold::CalThreshold(vector<unsigned int> v, int H, int W, int F)
{
	Height=H;
	Width=W;
	Frames=F;
	GetPiTable(v);
	int i,Maxi;
	double max=0;
	for (i=0;i<256;i++)
	{
		GetUk(i);
		deltak[i]=(u*wk0-uk0)*(u*wk0-uk0)/(wk0*wk1);
		if (deltak[i]>=max)
		{
			max=deltak[i];
			Maxi=i;
		}
	}
	return Maxi;
}

void AutoThreshold::GetUk(int k)
{
	uk0=0;
	wk0=0;
	for (long i=0;i<=k;i++)
	{
		uk0+=i*Pi[i];
		wk0+=Pi[i];
	}
	uk1=u-uk0;
	wk1=1-wk0;
}